<?php
namespace newMobile\Controller;
use Think\Controller;
class StoreApiController extends Controller {
    public function _initialize()
    {
        //parent::_initialize();
        header('Content-Type:application/json;charset=utf-8 ');
        vendor('Weixinpay.WxPayPubHelper');
        vendor('Weixinpay.wechatH5Pay');
        $redis =connectRedis();
        $uid=$redis->get('user_id');
        $store_id=$_GET['store_id'];
        if(empty($store_id)){
            $store_id=$redis->get('store_id');
        }
        if(empty($store_id)){
            $this->ajax_r(3,'店铺信息已失效');
        }
        $redis->set('store_id',$store_id);
        $store = M('store');
        $store_info = $store->find($store_id);
        if ($store_info['status'] == 0) {
            $this->ajax_r(0,'该店铺已关闭');
        }
        $this->uid =$uid;
        $this->store_id =$store_id;
        /*header("Access-Control-Allow-Origin: *");
        header("Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Requested-With");
        header('Access-Control-Allow-Methods: GET, POST, OPTIONS');*/
    }

    public function wx_in()
    {
        $code=$_GET["code"];
        $store_id=intval($_GET["store_id"]);
        if (empty($code)||empty($store_id)) {
            $this->ajax_r(0,'参数为空！');
        }
        $store='wx_store_'.$store_id;
        $appid = C($store.'.WEIXIN_APP_KEY');
        $appsecret = C($store.'.WEIXIN_APP_SECRET');
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret='.$appsecret.'&js_code='.$code .'&grant_type=authorization_code';
        $rs1 = file_get_contents($url);
        $rs = json_decode($rs1, TRUE);
        //\Think\Log::write("session :\n" . print_r($rs, true) . "\n",'storeApi/session' . date('Y-m-d'));
        if(empty($rs['errcode'])){
            $rd_session=$this->rd_session(16);
            $redis =connectRedis();
            $redis->set('rd_session',$rd_session);
            $redis->set('session_key',$rs['session_key']);
            $redis->set('openid',$rs['openid']);
            $data['rd_session']=$rd_session;
            $this->ajax_r(1,'成功',$data);
        }else{
            die($rs1);
        }
    }


    public function auth(){
        $rd_session=I('post.rd_session');
        $rawData=$_POST['rawData'];
        $signature=I('post.signature');
        if (empty($rd_session)||empty($rawData)||empty($signature)) {
            $this->ajax_r(0,'参数为空！');
        }
        $redis =connectRedis();
        $rd_redis=$redis->get('rd_session');
        //file_put_contents("session.txt", date("Y-m-d H:i:s") . "redis22  " .print_r($session, true). "\r\n", FILE_APPEND);
        $session_key=$redis->get('session_key');
        $openid=$redis->get('openid');
        if($rd_session!==$rd_redis){
            $this->ajax_r(0,'session已过期！');
        }
        $str=$rawData.$session_key;
        $signature1 = sha1($str);
        if($signature!=$signature1){
            $this->ajax_r(0,'签名数据不正确！');
        }
        $is_bd=0;
        if($openid){
            $weixin_info=$rawData;
            $weixin_info=json_decode($weixin_info,true);
            //用户已登录
            if(session('user_id')){
                $user_id=session('user_id');
                $user_info=M('users')->find($user_id);
                if($user_info){
                    if($user_info['phone']){
                        $is_bd=1;
                    }
                    if($user_info['wx_openid']==null){
                        $info['id']=$user_id;
                        $info['wx_rtopenid']=$openid;
                        $info['wx_name']=$weixin_info['nickname'];
                        M('users')->save($info);
                    }
                }
            }else{
                $youke_info=M('users')->where("wx_rtopenid='".$openid."'")->find();
                //file_put_contents("session.txt", date("Y-m-d H:i:s") . "youke_info  " .print_r($youke_info, true). "\r\n", FILE_APPEND);
                //未登陆
                $zd_out=session('zd_out');
                if($youke_info&&$zd_out!=1){
                    if($youke_info['phone']){
                        $is_bd=1;
                    }
                    $user_id=$youke_info['id'];
                }elseif($zd_out!=1){
                    //不存在创建游客账号,不是主动注销
                    $youke['username']=$weixin_info['nickname'];
                    $youke['password']="8888888";
                    $youke['wx_name']=$weixin_info['nickname'];
                    $youke['ishidden']=1;
                    $youke['addtime']=time();
                    $youke['user_pic']=$weixin_info['avatarUrl'];
                    $youke['login_time']=date('Y-m-d H:i:s',time());
                    $youke['sex']=$weixin_info['gender'];
                    $youke['wx_rtopenid']=$openid;
                    $youke['type']=1;
                    //file_put_contents("session.txt", date("Y-m-d H:i:s") . "youke  " .print_r($youke, true). "\r\n", FILE_APPEND);
                    $youke_id=M('users')->add($youke);
                    $user_id=$youke_id;
                }
            }
        }
        $data=array();
        if($user_id){
            $data['user_id']=$user_id;
            $data['is_bd']=$is_bd;
            $this->ajax_r(1,'成功',$data);
        }else{
            $this->ajax_r(0,'失败');
        }
    }
    public function bd(){
        if($_POST){
            $users=M('users');
            $post=I('post.');
            $uid=$post['uid'];
            $moblie=$post['phone'];
            $sms_captcha=$post['code'];
            if (empty($uid)||empty($moblie)||empty($sms_captcha)) {
                $this->ajax_r(0,'参数为空！');
            }
            $redis =connectRedis();
            $code=$redis->get($moblie);
            $userInfo=M('users')->find($uid);
            file_put_contents("session.txt", date("Y-m-d H:i:s") . "userInfo  " .print_r($userInfo, true). "\r\n", FILE_APPEND);
            if (empty($userInfo)) {
                $this->ajax_r(0,'该用户不存在！');
            }
            if($code){
                if($code==$sms_captcha){
                    $data['is_bd']=1;
                    $mobile_user=M('users')->where("phone='".$moblie."'")->find();
                    if($mobile_user){
                        if($mobile_user['id']==$uid){
                            $this->ajax_r(0,'你已绑定过该手机号！',$data);
                        }else{
                            $info['id']=$mobile_user['id'];
                            $info['wx_rtopenid']=$userInfo['wx_rtopenid'];
                            $info['wx_name']=$userInfo['wx_name'];
                            file_put_contents("session.txt", date("Y-m-d H:i:s") . "info  " .print_r($info, true). "\r\n", FILE_APPEND);
                            $rs=M('users')->save($info);
                            if($rs){
                                M('users')->where('id='.$uid)->delete();
                            }
                        }
                        $now_uid=$mobile_user['id'];
                    }else{
                        $info['id']=$uid;
                        $info['phone']=$moblie;
                        $rs=M('users')->save($info);
                        $now_uid=$uid;
                    }
                    if($rs){
                        $data['uid']=$now_uid;
                        $this->ajax_r(1,'绑定成功',$data);
                    }
                }else{
                    $this->ajax_r(0,'短信验证码错误');
                }
            }else{
                $this->ajax_r(0,'短信验证码失效');
            }

        }
    }
    public function sendCode(){
        $data=I('post.');
        $moblie=$data['phone'];
        $code=rand(1000,9999);
        $rs=duanxin($code,$moblie);
        if($rs['resultcode']==0){
            $redis =connectRedis();
            $redis->set($moblie,$code);
            $this->ajax_r(1,'发送成功！');
        }else{
            $data['error']=$rs['errordescription'];
            $this->ajax_r(0,'发送失败！',$data);
        }
    }
    //首页热销和最新产品
    public function index(){
        $store_id = trim(I('get.id'));
        $datas=array();
        if (empty($store_id)) {
            $datas['status'] = 0;
            $datas['message'] = '参数为空';
            $datas = json_encode($datas);
            die($datas);
        }
        $store = M('store');
        $store_info = $store->find($store_id);
        if ($store_info['status'] == 0) {
            $datas['status'] = 0;
            $datas['message'] = '该店铺已关闭';
            $datas = json_encode($datas);
            die($datas);
        }
        $lastId = intval(I('post.lastId', 0));
        $Num = trim(I('post.num', 10));
        $shop = M('shop');
        $where='';
        if ($lastId) {
            $where=' and ( id<"'.$lastId.'") ';
        }
        $shop_list =$shop->where('ishidden=0 and store_id=' . $store_id.$where)->order('sale_num desc,id desc')->limit(0, $Num)->select();

        if ($shop_list) {
            $datas['status'] = 1;
            $datas['message'] = '成功';
            $datas['data'] = $shop_list;
        } else {
            $datas['status'] = 0;
            $datas['message'] = '该店铺没有商品,请联系管理员';
        }
        $datas = json_encode($datas);
        die($datas);
    }



    //获取店铺信息
    public function getStoreInfo()
    {
        $store_id = I('get.id');
        $user_id = I('get.uid');
        if (empty($store_id)) {
            $datas['status'] = 0;
            $datas['message'] = '参数为空';
            $datas = json_encode($datas);
            die($datas);
        }
        $store = M('store');
        $store_info = $store->find($store_id);
        if ($store_info['status'] == 0) {
            $datas['status'] = 0;
            $datas['message'] = '该店铺已关闭';
            $datas = json_encode($datas);
            die($datas);
        }
        $data=array();
        $data['store_info']=$store_info;
        //店铺详情
        $store_template = M('store_template');
        $store_template_info = $store_template->where('store_id=' . $store_id)->find();
        $data['store_template_info']=$store_template_info;
        //店铺所在地
        $address['Province']=getProvinceInfo($store_info['province']);
        $address['City']=getCityInfo($store_info['city']);
        $address['District']=getDistrictInfo($store_info['district']);
        $data['address']=$address;

        $shop = M('shop');
        $count = $shop->where("store_id=$store_id and ishidden=0")->count();
        $data['shop_count']=$count;
        $coupon_goods = M('coupon_goods');
        $count_coupon = $coupon_goods
            ->join('yt_shop on yt_shop.id=yt_coupon_goods.goods_id', 'left')
            ->join('yt_coupon_type on yt_coupon_type.coupon_type_id=yt_coupon_goods.coupon_type_id', 'left')
            ->where("yt_coupon_type.store_id=$store_id and yt_shop.ishidden=0")->count();
        //echo $coupon_goods->_sql();
        $data['count_coupon']=$count_coupon;
        //判断收藏
        $users_storecollect = M('users_storecollect');
        if ($user_id) {
            $newstoreinfo['shore_id'] = $store_id;
            $newstoreinfo['user_id'] = $user_id;
            $rsstoreinfo = $users_storecollect->where($newstoreinfo)->select();
            if ($rsstoreinfo) {
                $storecollect_status = 1;
            } else {
                $storecollect_status = 0;
            }
        } else {
            $storecollect_status = 0;
        }
        $data['storecollect_status']=$storecollect_status;
        if (!empty($data)) {
            $datas['status'] = 1;
            $datas['message'] = '成功';
            $datas['data'] = $data;
        } else {
            $datas['status'] = 0;
            $datas['message'] = '该店铺没有信息,请联系管理员';
        }
        $datas = json_encode($datas);
        die($datas);

    }
    //首页热销和最新商品
    public function getIndex(){
        $store_id = trim(I('get.id'));
        $datas=array();
        if (empty($store_id)) {
            $datas['status'] = 0;
            $datas['message'] = '参数为空';
            $datas = json_encode($datas);
            die($datas);
        }
        $store = M('store');
        $store_info = $store->find($store_id);
        if ($store_info['status'] == 0) {
            $datas['status'] = 0;
            $datas['message'] = '该店铺已关闭';
            $datas = json_encode($datas);
            die($datas);
        }
        $lastId = intval(I('post.lastId', 0));
        $Num = trim(I('post.num', 10));
        $shop = M('shop');
        $where='';
        if ($lastId) {
            $where=' and ( id<"'.$lastId.'") ';
        }
        $shop_list = $shop->field('yt_shop.id,yt_shop.store_id,yt_shop.type_id,yt_shop.store_type_id,yt_shop.crowdfunding_id,yt_shop.title,yt_shop.image,yt_shop.click_num,yt_shop.price,yt_shop.oprice,yt_shop.sale_num,yt_shop.num,yt_shop.tuanselect,yt_shop.is_crowdfunding,yt_shop.dikouquan,yt_shop.envelope_type,yt_shop.redenvelope,yt_shop.envelope_product_id')
            ->where('ishidden=0 and store_id=' . $store_id.$where)->order('sale_num desc,id desc')->limit(0, $Num)->select();
        if ($shop_list) {
            $datas['status'] = 1;
            $datas['message'] = '成功';
            $datas['data'] = $shop_list;
        } else {
            $datas['status'] = 0;
            $datas['message'] = '该店铺没有商品,请联系管理员';
        }
        $datas = json_encode($datas);
        die($datas);
    }

    //根据分类获取商品
    public function getShopListByCat()
    {
        //print_r($_GET);
        $label = intval(I('get.label',1)); //标签id
        $type = intval(I('get.type',0)); //分类id
        //file_put_contents("session.txt", date("Y-m-d H:i:s") . "getStoreInfo_UID  " .print_r(session('user_id'), true). "\r\n", FILE_APPEND);
        //print_r($label);
        $store_id = trim(I('get.store_id'));
        if (empty($store_id)) {
            $datas['status'] = 0;
            $datas['message'] = '参数为空';
            $datas = json_encode($datas);
            die($datas);
        }
        $store = M('store');
        $store_info = $store->find($store_id);
        if ($store_info['status'] == 0) {
            $datas['status'] = 0;
            $datas['message'] = '该店铺已关闭';
            $datas = json_encode($datas);
            die($datas);
        }
        $lastId = intval(I('get.lastId'));
        $Num = trim(I('get.num', 10));
        $shop = M('shop');
        $orders = array(
            '1' => 'id desc',
            '2' => 'sale_num desc',
            '3' => 'click_num desc',
            '4' => 'price desc',
            '5' => 'price asc',
        );
        $where = '';
        if (!empty($type)) {
            $where = " and  FIND_IN_SET('$type',store_type_id)";
        }
        if (!empty($lastId)) {
            $shopdetails=$shop->field('yt_shop.id,yt_shop.sale_num,yt_shop.click_num,yt_shop.price')->find($lastId);
            if(empty($shopdetails)){
                $this->ajax_r(0,'参数错误！');
            }
            if($label==1){
                $where=' and ( id<"'.$lastId.'") ';
            }elseif($label==2){
                $sale_num=$shopdetails['sale_num'];
                $where=' and ( sale_num<="'.$sale_num.'") and  id!='.$lastId;
            }elseif($label==3){
                $click_num=$shopdetails['click_num'];
                $where=' and ( click_num<="'.$click_num.'") and  id!='.$lastId;
            }elseif($label==4){
                $price=$shopdetails['price'];
                $where=' and ( price<="'.$price.'") and  id!='.$lastId;
            }elseif($label==5){
                $price=$shopdetails['price'];
                $where=' and ( price>="'.$price.'") and  id!='.$lastId;
            }
        }
        $shop_list =$shop->field('yt_shop.id,yt_shop.store_id,yt_shop.type_id,yt_shop.store_type_id,yt_shop.crowdfunding_id,yt_shop.title,yt_shop.image,yt_shop.click_num,yt_shop.price,yt_shop.oprice,yt_shop.sale_num,yt_shop.num,yt_shop.tuanselect,yt_shop.is_crowdfunding,yt_shop.dikouquan,yt_shop.envelope_type,yt_shop.redenvelope,yt_shop.envelope_product_id')
            ->where('ishidden=0 and store_id='.$store_id . $where)
            ->order($orders[$label])
            ->limit(0, $Num)
            ->select();
        //print_r($shop->getLastSql());
        if ($shop_list) {
            $datas['status'] = 1;
            $datas['message'] = '成功';
            $datas['data'] = $shop_list;
        } else {
            $datas['status'] = 0;
            $datas['message'] = '暂无该类商品';
        }
        $datas = json_encode($datas);
        die($datas);
    }
    //获取店铺优惠券
    public function getStoreCoupons(){
        //分类
        $user_id=trim(I('get.uid'));
        $store_id = trim(I('get.store_id'));
        /*$page = intval(I('get.page',0));
        $Num = trim(I('get.num', 10));
        $lastId=($page-1)*$Num;*/
        if (empty($store_id)) {
            $datas['status'] = 0;
            $datas['message'] = '参数为空';
            $datas = json_encode($datas);
            die($datas);
        }
        $store = M('store');
        $store_info = $store->find($store_id);
        if ($store_info['status'] == 0) {
            $datas['status'] = 0;
            $datas['message'] = '该店铺已关闭';
            $datas = json_encode($datas);
            die($datas);
        }

        $coupon_goods=M('coupon_goods');
        $goods_ids=$coupon_goods->field('goods_id')->group('goods_id')->select();
        $new_goods_ids=array();
        foreach($goods_ids as $key =>$value){
            $new_goods_ids[]=$value['goods_id'];
        }
        $new_goods_ids=implode(',',$new_goods_ids);
        $shop=M('shop');
        $where_lianhe="ishidden=0  and id IN ($new_goods_ids)";//联合查询条件
        if($store_id>0){
            $where_lianhe=$where_lianhe.' and store_id='.$store_id;
        }
        $rs=$shop->where($where_lianhe)->select();
        foreach($rs as $key=>$value){
            //获取优惠券
            $coupon_goods=M('coupon_goods');
            $coupon_type_id=$coupon_goods->field('coupon_type_id')->where("goods_id=".$value['id'])->group('coupon_type_id')->select();
            foreach($coupon_type_id as $k=>$v){
                if($k==0){
                    $coupon_type_ids=$v['coupon_type_id'];
                }else{
                    $coupon_type_ids=','.$v['coupon_type_id'];
                }
            }
            //print_r($coupon_type_ids);
            $coupon_type=M('coupon_type');
            $map['coupon_type_id']  = array('in',$coupon_type_ids);
            $map['range_type']  = 1;
            $map['_logic'] = 'OR';
            $coupons=$coupon_type->where($map)->select();
            //print_r($coupons);
            $coupons_i=0;
            $couponsList=array();
            if($coupons){
                foreach($coupons as $k1=>$v1){
                    $start_time=strtotime($v1['start_time']);
                    $end_time=strtotime($v1['end_time']);
                    $nowtime=time();
                    if($start_time<=$nowtime && $end_time>=$nowtime){
                        $couponsList[$coupons_i]['shop_id'] = $value['id'];
                        $couponsList[$coupons_i]['shopName'] = $value['title'];
                        $couponsList[$coupons_i]['image'] = $value['image'];
                        $couponsList[$coupons_i]['price'] = $value['price'];
                        $couponsList[$coupons_i]['oprice'] = $value['oprice'];
                        $couponsList[$coupons_i]['coupons'] = $v1;
                        if ($user_id) {
                            $rs = get_coupon_user($user_id, $v['coupon_type_id']);
                            if ($rs['num'] >= $rs['max_fetch']) {
                                $couponsList[$coupons_i]['coupons_status'] = '2'; //2为已领取
                            } else {
                                $couponsList[$coupons_i]['coupons_status'] = '1';//1为未领取
                            }
                        } else {
                            $couponsList[$coupons_i]['coupons_status'] = '1';//1为未领取
                        }
                        $coupons_i++;
                    }
                }
            }
        }
        //print_r($couponsList);
        /*$pnum = ceil(count($couponsList)/$Num);
        $couponsList_show=array_slice($couponsList,$lastId, $Num);
        $data['total_page']=$pnum;*/
        //$data['page']=$pnum;
        //$data['total_num']=count($couponsList);
        $data['data']=$couponsList;
        if (!empty($couponsList)) {
            $datas['status'] = 1;
            $datas['message'] = '成功';
            $datas['datas'] = $data;
        } else {
            $datas['status'] = 0;
            $datas['message'] = '无优惠券';
        }
        $datas = json_encode($datas);
        die($datas);

        //$shoplist=$shop->where("store_id='$store_id' and id in (SELECT goods_id from yt_coupon_goods group BY goods_id)")->select();
        //print_r($shop->getLastSql());
        /*$couponsList=array();
        $i=0;
        foreach($shoplist as $key=>$value) {
            //获取优惠券
            $coupon_goods = M('coupon_goods');
            $coupon_type_id = $coupon_goods->field('coupon_type_id')->where("goods_id=" . $value['id'])->group('coupon_type_id')->select();
            $coupon_type_ids=array();
            if(is_array($coupon_type_id)){
                foreach ($coupon_type_id as $typekey=>$typeValue){
                    $coupon_type_ids[$typekey]=$typeValue['coupon_type_id'];
                }
            }
            $map['coupon_type_id']  = array('in',$coupon_type_ids);
            $map['range_type']  = 1;
            $map['_logic'] = 'OR';
            $coupon_type = M('coupon_type');
            $coupons = $coupon_type->where($map)->find();
            //print_r($coupon_type->getLastSql());
            foreach ($coupons as $k => $v) {
                $couponsList[$i]['shop_id'] = $value['id'];
                $couponsList[$i]['shopName'] = $value['title'];
                $couponsList[$i]['image'] = $value['image'];
                $couponsList[$i]['price'] = $value['price'];
                $couponsList[$i]['oprice'] = $value['oprice'];
                $couponsList[$i]['coupons'] = $v;
                $start_time = strtotime($v['start_time']);
                $end_time = strtotime($v['end_time']);
                $nowtime = time();
                if ($start_time > $nowtime && $end_time >= $nowtime) {
                    $couponsList[$i]['coupons_status'] = '0';//0为未开始
                } elseif ($start_time <= $nowtime && $end_time >= $nowtime) {
                    if ($user_id) {
                        $rs = get_coupon_user($user_id, $v['coupon_type_id']);
                        if ($rs['num'] >= $rs['max_fetch']) {
                            $couponsList[$i]['coupons_status'] = '2'; //2为已领取
                        } else {
                            $couponsList[$i]['coupons_status'] = '1';//1为未领取
                        }
                    } else {
                        $couponsList[$i]['coupons_status'] = '1';//1为未领取
                    }
                } else {
                    $couponsList[$i]['coupons_status'] = '3';//3为已结束
                }
                $i++;
            }
        }*/

    }

    function myCoupons(){

        /*$page = intval(I('get.page',0));
        $Num = trim(I('get.num', 10));
        $lastId=($page-1)*$Num;*/
        $store_id=I('get.store_id');
        $uid=I('get.uid');

        /*if (!empty($lastId)) {
            $where=' and ( yt_coupon.coupon_id<"'.$lastId.'") ';
        }*/
        $couponModel=M('coupon');
        $where='';
        $time=date('Y-m-d H:i:s',time());
        $coupons=$couponModel
            ->field('yt_coupon_type.*,yt_coupon.coupon_code,yt_coupon.coupon_id')
            ->join('yt_coupon_type on yt_coupon_type.coupon_type_id =yt_coupon.coupon_type_id')
            ->where("yt_coupon.uid=$uid and yt_coupon.end_time>='$time' ".$where)
            ->order('yt_coupon.coupon_id desc,yt_coupon.end_time desc')
            ->select();
        $coupon_goods_Model=M('coupon_goods');
        $shopModel=M('shop');
        $coupons_i=0;
        $couponsList=array();
        if(is_array($coupons)){
            foreach ($coupons as $key=>$value){
                $coupon_type_id=$value['coupon_type_id'];
                $coupon_goods=$coupon_goods_Model->where("coupon_type_id=".$coupon_type_id)->select();
                if(is_array($coupon_goods)){
                    foreach ($coupon_goods as $k=>$v){
                        $good_id=$v['goods_id'];
                        $shops=$shopModel->field('yt_shop.id,yt_shop.title,yt_shop.image,yt_shop.price,yt_shop.oprice')->find($good_id);
                        $couponsList[$coupons_i]['shop_id'] = $shops['id'];
                        $couponsList[$coupons_i]['shopName'] = $shops['title'];
                        $couponsList[$coupons_i]['image'] = $shops['image'];
                        $couponsList[$coupons_i]['price'] = $shops['price'];
                        $couponsList[$coupons_i]['oprice'] = $shops['oprice'];
                        $couponsList[$coupons_i]['coupons'] = $value;
                        $coupons_i++;
                    }
                }
            }
        }
        //print_r($couponsList);
        /*$pnum = ceil(count($count)/$Num);
        $pnum = ceil(count($couponsList)/$Num);
        $couponsList_show=array_slice($couponsList,$lastId, $Num);*/
        //$data['total_page']=count($couponsList);
        //$data['page']=$pnum;
        $data['total_num']=count($couponsList);
        $data['data']=$couponsList;
        if (!empty($couponsList)) {
            $datas['status'] = 1;
            $datas['message'] = '成功';
            $datas['datas'] = $data;
        } else {
            $datas['status'] = 0;
            $datas['message'] = '暂未领取任何优惠券';
        }
        $datas = json_encode($datas);
        die($datas);
    }

    public function getCoupon(){
        $id=I('get.id');
        $uid=I('get.uid');
        if (empty($id)) {
            $this->ajax_r(0,'参数为空');
        }
        if($uid){
            $coupon_type=M('coupon_type');
            $coupon=M('coupon');
            $coupon_info=$coupon_type->find($id);
            $count=$coupon->where("coupon_type_id=$id and uid=$uid")->count();
            if($count>=$coupon_info['max_fetch']&&$coupon_info['max_fetch']!=0){
                $code=0;
                $message='您已领取超过该优惠券最大领取个数 ！';
            }else{
                $rs=$coupon->where("coupon_type_id=$id and uid=0")->find();
                if($rs){
                    $data['coupon_id']=$rs['coupon_id'];
                    $data['uid']=$uid;
                    $data['fetch_time']=date('Y-m-d H:i:s',time());
                    $data['state']=1;
                    $rs=$coupon->save($data);
                    $code=1;
                    $message='领取成功！';
                }else{
                    $code=0;
                    $message='没有剩余优惠券了！';
                }
            }
        }else{
            $code=0;
            $message='您还未登陆！！';
        }
        $this->ajax_r($code,$message);
    }

    public function getShopDetails(){
        $id=I('get.id');
        $uid=I('get.uid');
        $rec_id=I('get.rec_id');
        if(empty($id)){
            $datas['status'] = 0;
            $datas['message'] = '参数为空';
            $datas = json_encode($datas);
            die($datas);
        }
        //足迹
        $shop=M('shop');
        $shop_info=$shop->find($id);
        if(!$shop_info){
            $datas['status'] = 0;
            $datas['message'] = '该产品不存在！';
            $datas = json_encode($datas);
            die($datas);
        }
        if($shop_info['ishidden']>0){
            $datas['status'] = 0;
            $datas['message'] = '该产品已下架！';
            $datas = json_encode($datas);
            die($datas);
        }
        $shopDetails=array();
        if($shop_info['is_crowdfunding']){
            $crowdfunding=M('crowdfunding');
            $crowdfunding_info=$crowdfunding->where("goods_id=$id")->find();
            $crowdfunding_info['surplus_time']=ShengYu_Tian_Shi_Fen(strtotime($crowdfunding_info['end_time']));
            $crowdfunding_info['percent']=round( $crowdfunding_info['now_money']/$crowdfunding_info['total_money'] * 100 , 2);
            $shopDetails['crowdfunding']=$crowdfunding_info;
        }
        if($rec_id){
            $rs=get_daiyan_status($id,$rec_id);
            if(!$rs){
                $datas['status'] = 0;
                $datas['message'] = '该用户无代言该产品资格！';
                $datas = json_encode($datas);
                die($datas);
            }else{
                if($uid){
                    $daiyan_info['uid']=$uid;
                    $daiyan_info['bid']=$rec_id;
                    $daiyan_info['shop_id']=$id;
                    $daiyan_info['time']=time();

                    $invoice=get_web_invoice();

                    $start_time=time()-60*60*24*$invoice['web_diyong'];
                    $daiyan=M('daiyan')->where("bid=$rec_id and shop_id=$id and time>$start_time and uid=$uid ")->find();

                    if(!$daiyan){
                        $daiyan_rs=M('daiyan')->add($daiyan_info);
                        $buser_info=M('users')->find($uid);
                        if($buser_info['wx_h5openid']&&$shop_info['dikouquan']>0){
                            $keyword1='58代言'.$shop_info['dikouquan'].'元现金抵扣券';
                            $keyword2=date('Y-m-d H:i:s',time());
                            send_info_dikouquan($buser_info['wx_h5openid'],$keyword1,$keyword2);
                        }
                        if($daiyan_rs&&$shop_info['dikouquan']>0){
                            $shopDetails['daiyan_rs']=1;
                        }
                    }
                }
            }
        }
        $daiyan_sale_where['uid']=$uid;
        $daiyan_sale_where['shop_id']=$id;
        $daiyan_sale=M('daiyan')->where($daiyan_sale_where)->find();
        if($daiyan_sale){
            $shopDetails['daiyan_sale']=$daiyan_sale;
        }
        $shop->where('id='.$id)->setInc('click_num',1);
        $shop_info['shop_sku']=json_decode($shop_info['shop_sku'],true);
        $shopDetails['shop_info']=$shop_info;
        //拼团
        if($shop_info['tuanselect']==1){
            $order=M('order');
            $rs_tuan=$order
                ->field('yt_order.order_id,yt_order.buyer_name,yt_order.buyer_mobile,yt_users.user_pic,yt_order.order_id,yt_order.payment_time,yt_order.tuannum,yt_order.buyer_city')
                ->join("yt_order_goods on yt_order_goods.order_id=yt_order.order_id")
                ->join("yt_users on yt_users.id=yt_order.buyer_id")
                ->where("yt_order.tuanselect=1 and yt_order.tuan_is_first_id=0 and yt_order_goods.goods_id=$id and yt_order.order_state='20' and yt_order.refund_state=0" )
                ->group('yt_order.order_id')
                ->select();
            foreach($rs_tuan as $key=>$v){
                $num=get_tuan($v['order_id']);
                $pt_nowtime=time();
                $close_time=$v['payment_time']+60*60*24;
                if($pt_nowtime<$close_time){
                    if($num<$v['tuannum']){
                        $v['num']=$v['tuannum']-$num;
                        $new_rs_tuan[]=$v;
                    }
                }
            }
            $shopDetails['new_rs_tuan']=$new_rs_tuan;
        }
        //获取相册
        $shop_content=M('shop_content');
        $shop_content_info=$shop_content->where('shop_id='.$id)->find();
        $shop_content_info['config']=json_decode($shop_content_info['config'],true);
        $shopDetails['shop_content_info']=$shop_content_info;
        $image_array=explode(',',$shop_content_info['gallery']);
        $shopDetails['arr_img']=$image_array;
        $order_goods_evaluate=M('order_goods_evaluate');
        //图片评价
        $img_evaluate_count=$order_goods_evaluate->where("goods_id=$id and  is_show=1 and  image <>''")->count();
        //好评
        $good_evaluate_count=$order_goods_evaluate->where("goods_id=$id and is_show=1 and (scores=5 or scores=4)")->count();
        //差评
        $bad_evaluate_count=$order_goods_evaluate->where("goods_id=$id and  is_show=1 and (scores=1 or scores=2)")->count();
        //中评
        $zhong_evaluate_count=$order_goods_evaluate->where("goods_id=$id and is_show=1 and scores=3")->count();
        $shopDetails['img_evaluate_count']=$img_evaluate_count;
        $shopDetails['good_evaluate_count']=$good_evaluate_count;
        $shopDetails['bad_evaluate_count']=$bad_evaluate_count;
        $shopDetails['zhong_evaluate_count']=$zhong_evaluate_count;
        //判断收藏
        $users_shopcollect=M('users_shopcollect');
        if($uid){
            $newshopinfo['shop_id']=$id;
            $newshopinfo['user_id']=$uid;
            $rsshopinfo=$users_shopcollect->where($newshopinfo)->select();
            //print_r($users_shopcollect->getLastSql());
            if($rsshopinfo){
                $rsshopinfo_status=1;
            }else{
                $rsshopinfo_status=0;
            }
        }else{
            $rsshopinfo_status=0;
        }
        $shopDetails['rsshopinfo_status']=$rsshopinfo_status;


        //获取优惠券
        $coupon_goods=M('coupon_goods');
        $coupon_type_id=$coupon_goods->field('coupon_type_id')->where("goods_id=$id")->group('coupon_type_id')->select();
        foreach($coupon_type_id as $key=>$value){
            if($key==0){
                $coupon_type_ids=$value['coupon_type_id'];
            }else{
                $coupon_type_ids=','.$value['coupon_type_id'];
            }
        }
        $coupon_type=M('coupon_type');
        $map['coupon_type_id']  = array('in',$coupon_type_ids);
        $map['range_type']  = 1;
        $map['_logic'] = 'OR';
        $coupons=$coupon_type->where($map)->select();
        $coupons_i=0;
        foreach($coupons as $key=>$value){
            $start_time=strtotime($value['start_time']);
            $end_time=strtotime($value['end_time']);
            $nowtime=time();
            if($start_time<=$nowtime && $end_time>=$nowtime){
                $new_coupons[$coupons_i]=$value;
                $coupons_i++;
            }
        }
        $shop_count=M('shop')->where('ishidden=0 and store_id='.$shop_info['store_id'])->count();
        $shop_store_count=M('users_storecollect')->where('shore_id='.$shop_info['store_id'])->count();
        $shopDetails['shop_count']=$shop_count;
        $shopDetails['shop_store_count']=$shop_store_count;
        $shopDetails['coupons']=$new_coupons;
        if (!empty($shopDetails)) {
            $datas['status'] = 1;
            $datas['message'] = '成功';
            $datas['datas'] = $shopDetails;
        } else {
            $datas['status'] = 0;
            $datas['message'] = '无商品信息';
        }
        $datas = json_encode($datas);
        die($datas);

    }

    public function getCategory(){
        $storeId = I('get.store_id');
        if (empty($storeId)) {
            $datas['status'] = 0;
            $datas['message'] = '参数为空';
            $datas = json_encode($datas);
            die($datas);
        }
        $nav_obj= M("store_type");
        $oldid=$storeId;
        $storeId= intval($storeId);

        $navs= $nav_obj->where(array('shore_id'=>$storeId,'status'=>1))->order(array("listorder" => "ASC"))->select();
        F("site_store_nav_".$oldid,$navs);
        import("Think.Tree");
        $tree = new \Tree();
        $tree->init($navs);
        $category=$tree->get_tree_array(0, "");
        if (!empty($category)) {
            $datas['status'] = 1;
            $datas['message'] = '成功';
            $datas['datas'] = $category;
        } else {
            $datas['status'] = 0;
            $datas['message'] = '该店铺暂无添加分类';
        }
        $datas = json_encode($datas);
        die($datas);
    }

    public  function  getEvaluate(){
        $id=I('get.id');
        if(empty($id)){
            $datas['status'] = 0;
            $datas['message'] = '参数为空';
            $datas = json_encode($datas);
            die($datas);
        }
        $lastId = intval(I('post.lastId', 0));
        $Num = trim(I('post.num', 10));
        $order_goods_evaluate=M('order_goods_evaluate');
        $where='';
        if (!empty($lastId)) {
            $where=' and ( id<"'.$lastId.'") ';
        }
        $count=$order_goods_evaluate->where("goods_id=$id and  is_show=1 ".$where)->order('id desc')->count();
        $evaluates['total_num']=$count;
        $evaluate=$order_goods_evaluate->where("goods_id=$id and  is_show=1".$where)->limit(0, $Num)->order('id desc')->select();
        //图片评价
        $img_evaluate_count=$order_goods_evaluate->where("goods_id=$id and  is_show=1 and  image <>''")->count();
        //好评
        $good_evaluate_count=$order_goods_evaluate->where("goods_id=$id and is_show=1 and (scores=5 or scores=4)")->count();
        //差评
        $bad_evaluate_count=$order_goods_evaluate->where("goods_id=$id and  is_show=1 and (scores=1 or scores=2)")->count();
        //中评
        $zhong_evaluate_count=$order_goods_evaluate->where("goods_id=$id and is_show=1 and scores=3")->count();
        $evaluates['img_evaluate_count']=$img_evaluate_count;
        $evaluates['good_evaluate_count']=$good_evaluate_count;
        $evaluates['bad_evaluate_count']=$bad_evaluate_count;
        $evaluates['zhong_evaluate_count']=$zhong_evaluate_count;
        $evaluates['evaluate']=$evaluate;

        if (!empty($evaluates)) {
            $datas['status'] = 1;
            $datas['message'] = '成功';
            $datas['datas'] = $evaluates;
        } else {
            $datas['status'] = 0;
            $datas['message'] = '无评论';
        }
        $datas = json_encode($datas);
        die($datas);
    }

    //收藏 type=1 为商品 2为店铺
    public function collect(){
        $user_id=intval(I('get.uid'));
        $data=I('get.');
        $user_id=$data['uid']?$data['uid']:'178';
        if($_GET&&$user_id){
            if($data['type']==1&&$data['id']){
                $newdata['shop_id']=$data['id'];
                $newdata['user_id']=$user_id;
                $users_shopcollect=M('users_shopcollect');
                $rs=$users_shopcollect->where($newdata)->select();
                if($rs){
                    $this->ajax_r(0,'该商品已收藏！');
                }else{
                    $newdata['addtime']=time();
                    $rs=$users_shopcollect->add($newdata);
                    $this->ajax_r(1,'收藏成功！');
                }
            }
            if($data['type']==2){
                $newdata['shore_id']=$data['id'];
                $newdata['user_id']=$user_id;
                $users_storecollect=M('users_storecollect');
                $rs=$users_storecollect->where($newdata)->select();
                if($rs){
                    $users_storecollect->where($newdata)->delete();
                    $this->ajax_r(2,'取消收藏成功！');
                }else{
                    $newdata['addtime']=time();
                    $rs=$users_storecollect->add($newdata);
                    $this->ajax_r(1,'收藏成功！');
                }
            }
        }else{
            $this->ajax_r(0,'请先登录！');
        }
    }
    //取消收藏 type=1 为商品 2为店铺
    public function delcollect(){
        $user_id=intval(I('get.uid'));
        $data=I('get.');
        $user_id=$data['uid']?$data['uid']:'178';
        if($_GET&&$user_id){
            if($data['type']==1&&$data['id']){
                $newdata['shop_id']=$data['id'];
                $newdata['user_id']=$user_id;
                $users_shopcollect=M('users_shopcollect');
                $rs=$users_shopcollect->where($newdata)->delete();
                if($rs){
                    $this->ajax_r(0,'取消成功！');
                }else{
                    $this->ajax_r(0,'取消失败！');
                }
            }
            if($data['type']==2){
                $newdata['shore_id']=$data['id'];
                $newdata['user_id']=$user_id;
                $users_storecollect=M('users_storecollect');
                $rs=$users_storecollect->where($newdata)->delete();
                print_r($users_storecollect->getLastSql());
                if($rs){
                    $this->ajax_r(0,'取消成功！');
                }else{
                    $this->ajax_r(0,'取消失败！');
                }
            }
        }
    }
    public function getCart()
    {
        $uid = I('get.uid');
        $storeId = I('get.store_id');
        if (empty($uid)&&empty($storeId)) {
            $datas['status'] = 0;
            $datas['message'] = '参数为空';
            $datas = json_encode($datas);
            die($datas);
        }
        $lastId = intval(I('get.lastId', 0));
        $Num = trim(I('get.num', 10));
        $shop = M('shop');
        $shop_sku = M('shop_sku');
        $count['num'] = 0;
        $count['price'] = 0;
        $where='';
        if ($lastId) {
            $where=' and ( id<"'.$lastId.'") ';
        }
        $cart = M('cart');
        $cart_list = $cart->where('buyer_id=' . $uid.' and store_id='.$storeId.$where)->order('cart_id desc')->limit(0, $Num)->select();
        //print_r($cart->getLastSql());
        $cart_info=array();
        foreach ($cart_list as $key => $v) {
            $shop_id=$v['shop_id'];
            $cart_id=$v['cart_id'];
            $rs_shop=$shop->find($shop_id);
            if(empty($rs_shop)){
                $cart->where("buyer_id=$uid and cart_id=$cart_id")->delete();
                continue;
            }
            $cart_info[$key]['cart_id'] = $cart_id;
            $cart_info[$key]['shop_picture'] = $rs_shop['image'];
            if ($v['sku_id'] != 0) {
                $rs_shop_sku = $shop_sku->where('sku_id=' . $v['sku_id'])->find();
                $cart_info[$key]['shop_name'] = $rs_shop['title'];
                $cart_info[$key]['sku_spec']=$rs_shop_sku['sku_spec'];
                $cart_info[$key]['sku_style']=$rs_shop_sku['sku_style'];
                if($v['tuanselect']==1){
                    if($rs_shop_sku['sku_price_tuan']){
                        $price=$rs_shop_sku['sku_price_tuan'];
                    }else{
                        $price=$rs_shop['tuan_price'];
                    }
                }else{
                    $price=$rs_shop_sku['sku_price'];
                }
            } else {
                $cart_info[$key]['shop_name'] = $rs_shop['title'];
                if($v['tuanselect']=='1'){
                    $price= $rs_shop['tuan_price'];
                }else{
                    $price= $rs_shop['price'];
                }
            }
            $invoice=get_web_invoice();
            $start_time=time()-60*60*24*$invoice['web_diyong'];
            $daiyan_info=M('daiyan')->where("uid=$uid and shop_id=$shop_id and time>$start_time")->find();

            if($daiyan_info){
                $cart_info[$key]['daiyan_sale']=$rs_shop['dikouquan'];
            }else{
                $cart_info[$key]['daiyan_sale']=0;
            }
            $cart_info[$key]['shop_id'] = $shop_id;
            $cart_info[$key]['sku_id'] = $v['sku_id'];
            $cart_info[$key]['oprice']=$rs_shop['oprice'];
            $cart_info[$key]['price']=$price;
            $cart_info[$key]['num']=$v['num'];
            $count['num'] = $count['num'] + $v['num'];
            $count['price'] = $count['price'] + ($v['num'] * $price);
        }
        $data['total_num'] = $count['num'];
        $data['total_price'] =$count['price'];
        $data['cart_info']=$cart_info;
        if (!empty($cart_info)) {
            $datas['status'] = 1;
            $datas['message'] = '成功';
            $datas['datas'] = $data;
        } else {
            $datas['status'] = 0;
            $datas['message'] = '购物车为空';
        }
        $datas = json_encode($datas);
        die($datas);
    }

    public function getTotalPrice()
    {
        $cartIds = I('get.Ids');
        //print_r($cartIds);
        if (empty($cartIds)) {
            $datas['status'] = 0;
            $datas['message'] = '参数为空';
            $datas = json_encode($datas);
            die($datas);
        }
        $cart = M('cart');
        $shop = M('shop');
        $shop_sku = M('shop_sku');
        $total_num= 0;
        $total_price = 0;

        $cartIdarray=explode(",",$cartIds);
        //print_r($cartIdarray);
        $cart_info=array();
        foreach ($cartIdarray as $key => $v) {
            $cartInfo=$cart->where("cart_id=$v")->find();
            $shop_id=$cartInfo['shop_id'];
            $rs_shop=$shop->find($shop_id);
            if(empty($rs_shop)){
                $cart->where("cart_id=$v")->delete();
                continue;
            }

            if ($cartInfo['sku_id'] != 0) {
                $rs_shop_sku = $shop_sku->where('sku_id=' . $cartInfo['sku_id'])->find();
                $cart_info[$key]['shop_name'] = $rs_shop['title'];
                $cart_info[$key]['sku_spec']=$rs_shop_sku['sku_spec'];
                $cart_info[$key]['sku_style']=$rs_shop_sku['sku_style'];
                if($cartInfo['tuanselect']==1){
                    if($rs_shop_sku['sku_price_tuan']){
                        $price=$rs_shop_sku['sku_price_tuan'];
                    }else{
                        $price=$rs_shop['tuan_price'];
                    }
                }else{
                    $price=$rs_shop_sku['sku_price'];
                }
            } else {
                $cart_info[$key]['shop_name'] = $rs_shop['title'];
                if($cartInfo['tuanselect']=='1'){
                    $price= $rs_shop['tuan_price'];
                }else{
                    $price= $rs_shop['price'];
                }
            }
            $uid=$cartInfo['buyer_id'];
            $invoice=get_web_invoice();
            $start_time=time()-60*60*24*$invoice['web_diyong'];
            $daiyan_info=M('daiyan')->where("uid=$uid and shop_id=$shop_id and time>$start_time")->find();
            if($daiyan_info){
                $daiyan_sale=$rs_shop['dikouquan'];
            }else{
                $daiyan_sale=0;
            }
            $total_num = $total_num + $cartInfo['num'];
            $total_price=$total_price+($cartInfo['num']*$price)-($cartInfo['num']*$daiyan_sale);
        }
        $data['total_num'] = $total_num;
        $data['total_price'] =$total_price;
        if (!empty($data)) {
            $datas['status'] = 1;
            $datas['message'] = '成功';
            $datas['datas'] = $data;
        } else {
            $datas['status'] = 0;
            $datas['message'] = '购物车为空';
        }
        $datas = json_encode($datas);
        die($datas);
    }






    //添加购物车
    public function add_cart()
    {
        $data = I('post.');
        $uid=$data['uid'];
        $shop_sku = M('shop_sku');
        $shop = M('shop');
        $buygood = I('get.buygood', 0);
        $shop_info = $shop->find($data['id']);
        $num = $data['num'] ? $data['num'] : 1;
        if(empty($data['id'])||empty($uid)){
            $this->ajax_r(0,'参数为空！');
        }
        //print_r($data['style']);
        if (isset($data['style']) || isset($data['spec'])) {
            //有属性
            $map['shop_id'] = $data['id'];
            if (isset($data['style'])) {
                $map['sku_style'] = $data['style'];
            }
            if (isset($data['spec'])) {
                $map['sku_spec'] = $data['spec'];
            }
            $sku_info = $shop_sku->where($map)->find();
        }else{
            $this->ajax_r(0,'请选择规格或样式！');
        }
        //整理添加数据
        $new_cart['shop_id'] = $data['id'];
        $new_cart['store_id'] = $shop_info['store_id'];
        $new_cart['num'] = $num;
        $new_cart['select'] = 1;
        //$new_cart['recommend_id']=$data['rec_id'];
        $new_cart['tuanselect'] = $data['tuanselect'] ? $data['tuanselect'] : 0;
        $new_cart['ctuan_id'] = $data['ctuan_id'] ? $data['ctuan_id'] : 0;
        if ($sku_info) {
            $new_cart['sku_id'] = $sku_info['sku_id'];
        } else {
            $new_cart['sku_id'] = 0;
        }
        $rs = addcart($uid, $new_cart['shop_id'], $new_cart['sku_id'], $new_cart['num'], $new_cart['tuanselect'], $new_cart['ctuan_id'], $buygood);
        if ($rs == 1) {
            $data['cart_id'] =session('cart_list_id');
            $this->ajax_r(1,'成功加入购物车！',$data);
        } elseif ($rs == 2) {
            $this->ajax_r(0,'不能参加自己所开的团！');
        } elseif ($rs == 3) {
            $this->ajax_r(0,'库存不足！');
        } elseif ($rs == 4) {
            $this->ajax_r(0,'该产品限购！');
        } elseif ($rs == 5) {
            $this->ajax_r(0,'不可重复参团！');
        } elseif ($rs == 6) {
            $this->ajax_r(0,'购买量不得小于起拍量！');
        } else {
            $this->ajax_r(0,'加入购物车失败！');
        }
    }

    function edit_cart()
    {
        if ($_GET) {
            $data = I('get.');
            $uid = $data['uid'];
            $cart_id = $data['id'];
            $num = 0;
            if (empty($cart_id) && empty($uid)) {
                $this->ajax_r(0,'参数为空！');

            }
            $sku_style = $data['style'];
            $sku_spec = $data['spec'];
            $cart = M('cart');
            $cart_info = $cart->find($cart_id);
            if (isset($sku_style) || isset($sku_spec)) {
                //有属性
                $map['shop_id'] = $cart_info['shop_id'];
                if (isset($sku_style)) {
                    $map['sku_style'] = $sku_style;
                }
                if (isset($sku_spec)) {
                    $map['sku_spec'] = $sku_spec;
                }
                $sku_info = M('shop_sku')->where($map)->find();
                $field['sku_id'] = $sku_info['sku_id'];
            }
            if ($data['type'] == 1) {
                $num = $cart_info['num'] + 1;
            } elseif ($data['type'] == 2) {
                $num = $cart_info['num'] - 1;
            } else {
                $num = $data['num'];
            }
            if ($num > 0) {
                $shop_info = M('shop')->find($cart_info['shop_id']);
                //检测限购  与起拍量
                if ($shop_info['xz_num'] > 0) {
                    if ($num > $shop_info['xz_num']) {
                        $this->ajax_r(0,'该产品限购！');
                    }
                }
                if ($shop_info['qp_num'] > 0) {
                    if ($num < $shop_info['qp_num']) {
                        $this->ajax_r(0,'购买量不能少于起拍量！');
                    }
                }
                $field['num'] = $num;
                $rs = $cart->where('cart_id=' . $cart_id . ' and buyer_id=' . $uid)->setField($field);
                $cart_info = $cart->find($cart_id);
                $data['sku_spec']=$cart_info['sku_spec'];
                $data['sku_style']=$cart_info['sku_style'];
                $data['num']=$cart_info['num'];
                //print_r($cart->getLastSql());
                if ($rs) {
                    $this->ajax_r(1,'购物车更新成功！',$data);
                } else {
                    $this->ajax_r(0,'购物车更新失败！');
                }
            } else {
                $rs = $cart->where('cart_id=' . $cart_id . ' and buyer_id=' . $uid)->delete();
                if ($rs) {
                    $this->ajax_r(1,'购物车更新成功！');
                } else {
                    $this->ajax_r(0,'更新失败！');
                }
            }
        }
    }

    public function del_cart(){
        $uid=I('get.uid');
        $cart_ids=I('get.ids');
        $cart_id=explode(',',$cart_ids);
        $cart=M('cart');
        if(is_array($cart_id)) {
            foreach ($cart_id as $key => $val) {
                $rs = $cart->where('buyer_id=' . $uid . ' and cart_id=' . $val)->delete();
            }
        }
        if($rs){
            $datas['status'] = 1;
            $datas['message'] ='删除成功';
        }else{
            $datas['status'] = 0;
            $datas['message'] ='删除失败';
        }
        $datas = json_encode($datas);
        die($datas);
    }

    //获取订单信息
    public function getOrderDetails(){
        $getData = I('get.');
        $uid = $getData['uid'];
        $store_id = $getData['store_id'];
        $cart_ids = $getData['cart_ids'];
        if(empty($uid)&&empty($store_id)&&empty($cart_ids)) {
            $datas['status'] = 0;
            $datas['message'] = '参数为空';
            $datas = json_encode($datas);
            die($datas);
        }
        //收货地址
        $address=$this->address($uid);
        /*$this->orderInfo($uid,$store_id,$cart_ids);
        die();*/
        //订单商品
        $orderInfo=$this->orderInfo($uid,$store_id,$cart_ids);
        if(empty($orderInfo)||empty($orderInfo['cart_list'])){
            $datas['status'] = 0;
            $datas['message'] = '没有订单信息，请先下单';
            $datas = json_encode($datas);
            die($datas);
        }
        //优惠券
        $coupon=M('coupon');
        $coupon_type=M('coupon_type');
        $rs_coupon=$coupon
            ->field('coupon_type_id,start_time,end_time')
            ->where("uid=$uid and state=1")
            ->group('coupon_type_id')
            ->select();
        $coupons_i=0;
        $new_coupon_shop_ids=$orderInfo['new_coupon_shop_ids'];
        $rs=M('coupon_goods')->field('coupon_type_id')->where("goods_id in ($new_coupon_shop_ids)")->group('coupon_type_id')->select();
        foreach($rs as $key =>$value){
            $new_rs[]=$value['coupon_type_id'];
        }
        $new_coupons=$total=array();
        foreach($rs_coupon as $key=>$value){
            //先判断是否是下单商品可使用的优惠券
            if(in_array($value['coupon_type_id'],$new_rs)){
                $start_time=strtotime($value['start_time']);
                $end_time=strtotime($value['end_time']);
                $nowtime=time();
                if($start_time<=$nowtime && $end_time>=$nowtime){
                    $rs_coupon_type=$coupon_type->find($value['coupon_type_id']);
                    //计算可用优惠券总价格
                    $rs_coupon_goods=M('coupon_goods')->where("coupon_type_id=".$value['coupon_type_id'])->select();
                    $count_price=0;
                    $new_coupon_shop_ids=explode(',',$new_coupon_shop_ids);
                    foreach($rs_coupon_goods as $key=>$value){
                        if(in_array($value['goods_id'],$new_coupon_shop_ids)){
                            $goods_ids[]=$value['goods_id'];
                        }
                    }
                    foreach($orderInfo as $key =>$value){
                        foreach($value as $k =>$v){
                            if(in_array($v['shop_id'],$goods_ids)){
                                $count_price=$count_price+($v['price']*$v['num']);
                            }
                        }
                    }
                    //判断价格
                    if($rs_coupon_type['at_least']==0||($rs_coupon_type['at_least']!=0&&$rs_coupon_type['at_least']<=$count_price)){
                        $new_coupons[$coupons_i]=$value;
                        $new_coupons[$coupons_i]['coupon_name']=$rs_coupon_type['coupon_name'];
                        $new_coupons[$coupons_i]['coupon_type_id']=$rs_coupon_type['coupon_type_id'];
                        $new_coupons[$coupons_i]['at_least']=$rs_coupon_type['at_least'];
                        $new_coupons[$coupons_i]['money']=$rs_coupon_type['money'];
                        if($rs_coupon_type['at_least']!=0){
                            $new_coupons[$coupons_i]['xcy']='满'.$rs_coupon_type['at_least'].'元,减'.$rs_coupon_type['money'].'元';
                        }else{
                            $new_coupons[$coupons_i]['xcy']='无限制,减'.$rs_coupon_type['money'].'元';
                        }
                        $coupons_i++;
                    }
                }
            }
        }
        $web_qita=get_web_invoice();
        $web_invoice=$web_qita['web_invoice'];
        $web_invoice_array=explode(',',$web_invoice);
        $data['orderInfo'] =$orderInfo;
        $data['address'] =$address;
        $data['coupons']=$new_coupons;
        $data['web_invoice'] =$web_invoice_array;
        $data['cart_ids'] =$cart_ids;
        if (!empty($data)) {
            $datas['status'] = 1;
            $datas['message'] = '成功';
            $datas['datas'] = $data;
        } else {
            $datas['status'] = 0;
            $datas['message'] = '订单信息为空';
        }
        $datas = json_encode($datas);
        die($datas);
    }



    //获取用户地址信息
    public function getAddress(){
        $user_id = I('get.uid');
        if (empty($user_id)) {
            $datas['status'] = 0;
            $datas['message'] = '参数为空';
            $datas = json_encode($datas);
            die($datas);
        }
        $users_address=M('users_address');
        $users_address=$users_address->where('user_id='.$user_id.' and is_default=1')->find();
        if (!empty($users_address)) {
            $datas['status'] = 1;
            $datas['message'] = '成功';
            $datas['datas'] = $users_address;
        } else {
            $datas['status'] = 0;
            $datas['message'] = '用户地址为空';
        }
        $datas = json_encode($datas);
        die($datas);
    }

    //生成订单 以下字段默认
    //支付单号
    //$data['pay_sn']
    //支付方式名称代码
    //$data['payment_code']
    //支付(付款)时间
    //$data['payment_time']
    //订单完成时间
    //$data['finnshed_time']
    //预存款支付金额
    //$data['pd_amount']
    //评价状态 0未评价，1已评价
    //$data['evaluation_state']
    //订单状态：0(已取消)10(默认):未付款;20:已付款;30:已发货;40:已收货;
    //$data['order_state']
    //退款状态:0是无退款,1是部分退款,2是全部退款
    //$data['refund_state']
    //锁定状态:0是正常,大于0是锁定,默认是0
    //$data['lock_state']
    //退款金额
    //$data['refund_amount']
    //延迟时间,默认为0
    //$data['delay_time']
    //物流单号
    //$data['shipping_code']
    //物流商家
    //$data['shipping_name']
    public function order()
    {
        //统计商品
        $getData = I('get.');
        $uid = $getData['uid'];
        $store_id = $getData['store_id'];
        $cart_ids = $getData['cart_ids'];
        if (empty($uid) && empty($store_id) && empty($cart_ids)) {
            $datas['status'] = 0;
            $datas['message'] = '参数为空';
            $datas = json_encode($datas);
            die($datas);
        }
        $user_info = M('users')->find($uid);
        if ($user_info['phone'] == null) {
            $datas['status'] = 0;
            $datas['message'] = '请先去个人中心-关联账户中绑定手机';
            $datas = json_encode($datas);
            die($datas);
        }
        //获取收货地址
        $user_address = get_user_address($uid);
        if ($user_address == null) {
            $datas['status'] = 0;
            $datas['message'] = '请添加收货地址';
            $datas = json_encode($datas);
            die($datas);
        }
        //收货地址
        $address = $this->address($uid);
        //$this->orderInfo($uid,$store_id,$cart_ids);
        //订单商品
        $orderInfo = $this->orderInfo($uid, $store_id, $cart_ids);
        if (empty($orderInfo)) {
            $datas['status'] = 0;
            $datas['message'] = '没有订单信息，请先下单';
            $datas = json_encode($datas);
            die($datas);
        }
        //总订单号
        $order_cn = $this->build_order_no();
        /*if($orderInfo&&$uid){
            foreach($orderInfo as $key=>$value){*/
        $data = array();
        $store = M('store');
        $store_info = $store->find($store_id);
        /*$count_price=0;
        $count_fee=0;
        foreach($value as $k=>$v){
            $count_price=$count_price+$v['price']*$v['num'];
            $count_fee=$count_fee+$v['freight'];
        }*/

        //订单总编号
        $data['order_cn'] = $order_cn;
        $order_sn = $this->build_order_no();
        //订单子编号
        $data['order_sn'] = $order_sn;
        //卖家店铺id
        $data['store_id'] = $store_id;
        //卖家店铺名称
        $data['store_name'] = $store_info['title'];
        //买家id
        $data['buyer_id'] = $uid;
        //买家收货地址ID
        $data['buyer_address_id'] = $user_address['address_id'];
        //收货姓名
        $data['buyer_name'] = $user_address['consigner'];
        //收货省
        $data['buyer_province'] = $user_address['province'];
        //收货市
        $data['buyer_city'] = $user_address['city'];
        //收货区域
        $data['buyer_district'] = $user_address['district'];
        //收货地址
        $data['buyer_address'] = $user_address['address'];
        //收货手机
        $data['buyer_mobile'] = $user_address['mobile'];
        //收货电话
        $data['buyer_phone'] = $user_address['phone'];
        //收货邮编
        $data['buyer_zip_code'] = $user_address['zip_code'];
        //订单生成时间
        $data['add_time'] = time();
        //1WEB2mobile
        $data['order_from'] = 1;
        //商品总价格
        $data['goods_amount'] = $orderInfo['total_price'];
        //订单总价格
        $data['order_amount'] = $orderInfo['total_price'] + $orderInfo['total_freight'];
        //运费
        $data['shipping_fee'] = $orderInfo['total_freight'];
        $data['invoice_status'] = $getData['invoice_status'] ? $getData['invoice_status'] : 0;
        //发票抬头
        $data['invoice_title'] = $getData['invoice_title'];
        //发票类型
        $data['invoice_content'] = $getData['invoice_content'];
        //留言
        $data['leavemessage'] = $getData['leavemessage'];
        //优惠券种类ID
        $data['coupon'] = $getData['coupon'];
        $order = M('order');
        $cart = M('cart');
        $order_goods = M('order_goods');
        //开启事物
        $order->startTrans();
        $cart->startTrans();
        $order_goods->startTrans();
        //判断条件
        $falg = true;
        $rs_order = $order->add($data);
        if (!$rs_order) {
            $falg = false;
        }
        $cart_list = $orderInfo['cart_list'];
        if(empty($cart_list)){
            $this->ajax_r('0','订单信息为空，请重新下单');
        }
        foreach ($cart_list as $key => $value) {
            $shop_info = M('shop')->find($value['shop_id']);
            //免发货设置
            $data['mian_send'] = $shop_info['mian_send'];
            if ($shop_info['is_crowdfunding'] == '1') {
                $data['order_type'] = 2;
            }
            //团购设置
            if ($value['tuanselect'] == 1) {
                $data['tuanselect'] = 1;
                $data['tuan_is_first_id'] = $value['tuan_id'];
                $tuan_rs = $shop_info;
                $data['tuannum'] = $tuan_rs['tuan_num'];
                if ($value['tuan_id']) {
                    $count_num = get_tuan($value['tuan_id']);
                    if ($count_num >= $data['tuannum']) {
                        $this->ajax_r(0, $data['order_cn'], '该团已满！');
                    }
                }
                $return = M('order')->find($value['tuan_id']);
                if ($return['refund_state'] > 0) {
                    $this->ajax_r(0, $data['order_cn'], '该团已过期！');
                }
            }
            //代言抵扣券 查看
            $shop_id = $value['shop_id'];
            $invoice = get_web_invoice();
            $start_time = time() - 60 * 60 * 24 * $invoice['web_diyong'];
            $daiyan_info = M('daiyan')->where("uid=$uid and shop_id=$shop_id and time>$start_time")->find();

            if ($daiyan_info) {
                $data['daiyan_sale'] = $shop_info['dikouquan'] * $value['num'];
            } else {
                $data['daiyan_sale'] = 0;
            }
            $order_good['order_id'] = $rs_order;
            $order_good['goods_id'] = $value['shop_id'];
            $order_good['goods_name'] = $value['shop_name'];
            $order_good['goods_price'] = $value['price'];
            $order_good['goods_num'] = $value['num'];

            $order_good['goods_image'] = $value['shop_picture'];
            $order_good['goods_pay_price'] = $value['price'] * $value['num'];
            $order_good['goods_sku'] = $value['sku_id'];
            $order_good['goods_sku_spec'] = $value['sku_spec'];
            $order_good['goods_sku_style'] = $value['sku_style'];
            //代言奖励写入
            $order_shop_id = $value['shop_id'];
            $order_daiyan_info = M('daiyan')->where("uid=$uid and shop_id=$order_shop_id")->find();
            if ($order_daiyan_info && $order_daiyan_info['bid'] != $order_daiyan_info['uid']) {
                $recommend_id = $order_daiyan_info['bid'];
            } else {
                $recommend_id = 0;
            }
            $order_good['recommend_id'] = $recommend_id;
            if ($recommend_id > 0) {
                $order_shop_info = M('shop')->find($value['shop_id']);
                $order_good['recommend_type'] = $order_shop_info['envelope_type'];
                //红包奖励
                if ($order_shop_info['envelope_type'] == 0) {
                    $order_good['recommend_price'] = $order_shop_info['redenvelope'] * $value['num'];
                    $order_good['recommend_shop_id'] = 0;
                    $order_good['recommend_shop_num'] = 0;
                }
                //礼品奖励
                if ($order_shop_info['envelope_type'] == 1) {
                    $order_good['recommend_price'] = 0;
                    $order_good['recommend_shop_id'] = $order_shop_info['envelope_product_id'];
                    if ($order_shop_info['envelope_product_type'] == 0) {
                        $order_good['recommend_shop_num'] = 1;
                    }
                    if ($order_shop_info['envelope_product_type'] == 1) {
                        $order_good['recommend_shop_num'] = $value['num'];
                    }
                }
            }
            $order_good['store_id'] = $value['store_id'];
            $order_good['buyer_id'] = $uid;
            $order_good['goods_type'] = 1;
            $order_good['freight'] = $value['freight'];
            $rs_good = $order_goods->add($order_good);
            if (!$rs_good) {
                $falg = false;
            }
            $rs_cart = $cart->delete($value['cart_id']);
            if (!$rs_cart) {
                $falg = false;
            }
        }
        if ($falg) {
            $order->commit();
            $cart->commit();
            $order_goods->commit();
            //添加订单信息到redis监控
            addredis($data['order_cn']);
            $datas['status'] = 1;
            $datas['message'] = '下单成功';
            $datas['order_cn'] = $data['order_cn'];
        } else {
            $order->rollback();
            $cart->rollback();
            $order_goods->rollback();
            $datas['status'] = 0;
            $datas['message'] = '失败';
        }
        $datas = json_encode($datas);
        die($datas);

    }
    //支付信息
    public function orderQuery(){
        $order_cn=I('get.order_no');
        if (empty($order_cn)) {
            $datas['status'] = 0;
            $datas['message'] = '参数为空';
            $datas = json_encode($datas);
            die($datas);
        }
        $total_price=0;
        $status=get_order_status($order_cn,'10');
        if($status){
            $order=M('order');
            $result=$order->where('order_cn='.$order_cn)->select();
            if($result){
                foreach($result as $key=>$value){
                    $order_status=$this->orderQuery2($value['order_cn'],$value['store_id']);
                    $order_status2=$this->orderQuery2($value['order_sn'],$value['store_id']);
                    if($order_status||$order_status2){
                        $this->ajax_r(2,'该订单已支付成功！');
                    }
                    $time=$value['add_time'];
                    if($value['coupon']!=null){
                        $youhui_price=get_coupon_price($value['buyer_id'],$value['coupon']);
                    }
                    $total_price=$total_price+$value['order_amount']-$value['daiyan_sale']-$youhui_price;
                }
            }else{
                $result=$order->where('order_sn='.$order_cn)->find();
                $order_status=$this->orderQuery2($result['order_cn'],$result['store_id']);
                $order_status2=$this->orderQuery2($result['order_sn'],$result['store_id']);
                if($order_status||$order_status2){
                    $this->ajax_r(2,'该订单已支付成功！');
                }
                $youhui_price=get_coupon_price($result['buyer_id'],$result['coupon']);
                $total_price=$result['order_amount']-$result['daiyan_sale']-$youhui_price;

            }
            $data['order_no']=$order_cn;
            $data['total_price']=$total_price;
            if($total_price<=0){
                update_order_status($_GET['order_cn'], $_GET['order_cn'],'20','无需支付');
                $this->ajax_r(2,'无需支付！');
            }else{
                $this->ajax_r(1,'成功！',$data);
            }
        }else{
            $this->ajax_r(0,'订单状态不正确，请检查！');
        }
    }
    //微信使用jsapi接口start
    function wechatpay(){
        $code=I('get.code');
        $order_cn=I('get.order_no');
        $store_id=I('get.store_id');
        $status=get_order_status($order_cn,'10');
        if($status){
            $order=M('order');
            $result=$order->where('order_cn='.$order_cn)->select();
            $count_price=0;
            if($result){
                foreach($result as $key=>$value){
                    //$goods=$order_goods->field('yt_order_goods.goods_name')->where('order_id='.$value['order_id'])->find();
                    if($value['coupon']!=null){
                        $youhui_price=get_coupon_price($value['buyer_id'],$value['coupon']);
                    }
                    $count_price=$count_price+$value['order_amount']-$value['daiyan_sale']-$youhui_price;
                }
            }else{
                $result=$order->where('order_sn='.$order_cn)->find();
                $youhui_price=get_coupon_price($result['buyer_id'],$result['coupon']);
                $count_price=$result['order_amount']-$result['daiyan_sale']-$youhui_price;
            }
            $store = M('store');
            $store_info = $store->find($store_id);
            $store_name=$store_info['title'];
            //=========步骤1：网页授权获取用户openid============
            $openIdResult =$this->getOpenId($code,$store_id);
            if(empty($openIdResult['errcode'])){
                $openid=$openIdResult['openid'];
            }else{
                die(json_encode($openIdResult));
            }
            //file_put_contents("pay.txt", date("Y-m-d H:i:s") . "total_fee   " .print_r($count_price*100, true). "\r\n", FILE_APPEND);
            //=========步骤2：使用统一支付接口，获取prepay_id============
            //使用统一支付接口
            $unifiedOrder = new \UnifiedOrder_pub();
            /*此处做数据库的查询  这里操作数据库把产品信息显示出来*/

            //设置统一支付接口参数
            //设置必填参数
            //appid已填,商户无需重复填写
            //mch_id已填,商户无需重复填写
            //noncestr已填,商户无需重复填写
            //spbill_create_ip已填,商户无需重复填写
            //sign已填,商户无需重复填写
            //

            //设置统一支付接口参数
            //设置必填参数
            $store='wx_store_'.$store_id;
            $appid = C($store.'.WEIXIN_APP_KEY');
            $mch_id = C($store.'.WEIXIN_MCHID');
            $key= C($store.'.WEIXIN_MCHID_KEY');
            $unifiedOrder->setAPPID($appid);
            $unifiedOrder->setMCHID($mch_id);
            $unifiedOrder->setMCHKEY($key);
            $unifiedOrder->setParameter("appid",$appid);//APPID
            $unifiedOrder->setParameter("mch_id",$mch_id);//商户号$openid
            //$unifiedOrder->setParameter("key",$key);//APPID
            //$unifiedOrder->setParameter("openid",$openid);//openid
            $unifiedOrder->setParameter("openid",$openid);//openid
            $unifiedOrder->setParameter("body",$store_name);//商品描述
            //自定义订单号，此处仅作举例
            $unifiedOrder->setParameter("out_trade_no",$order_cn);//商户订单号
            $unifiedOrder->setParameter("total_fee",$count_price*100);//总金额
            $unifiedOrder->setParameter("notify_url",'https://m.58daiyan.com/StoreApi/wxnotify');//通知地址
            $unifiedOrder->setParameter("trade_type","JSAPI");//交易类型
            //非必填参数，商户可根据实际情况选填
            //$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号
            //$unifiedOrder->setParameter("device_info","XXXX");//设备号
            //$unifiedOrder->setParameter("attach","XXXX");//附加数据
            //$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
            //$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间
            //$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记
            //$unifiedOrder->setParameter("openid","XXXX");//用户标识
            //$unifiedOrder->setParameter("product_id","XXXX");//商品ID


            // print_r($unifiedOrderResult);
            //从统一支付接口获取到code_url(二维码)

            //商户自行增加处理流程
            //......
            //file_put_contents("sign.txt", date("Y-m-d H:i:s") . "unifiedOrder接口   " .print_r('unifiedOrder接口', true). "\r\n", FILE_APPEND);

            $prepay_id = $unifiedOrder->getPrepayId();
            //$prepay_id = $unifiedOrder->getRoutinePrepayId($appid,$mch_id,$key);
            if($prepay_id['return_code']=='FAIL'){
                $this->ajax_r(0,$prepay_id['return_msg']);
            }
            //$prepay_id=$prepay_id['prepay_id'];
            // print_r($prepay_id);

            // echo $prepay_id;exit();
            //=========步骤3：使用jsapi调起支付============
            // file_put_contents("sign.txt", date("Y-m-d H:i:s") . "JsApi_pub接口   " .print_r('JsApi_pub接口', true). "\r\n", FILE_APPEND);

            $jsApi = new \JsApi_pub();
            $jsApi->setAPPID($appid);
            $jsApi->setMCHID($mch_id);
            $jsApi->setMCHKEY($key);
            $jsApi->setPrepayId($prepay_id);

            $jsApiParameters = $jsApi->getParameters();
            // file_put_contents("sign.txt", date("Y-m-d H:i:s") . "jsApiObj   " .print_r($jsApiParameters, true). "\r\n", FILE_APPEND);

            //print_r($jsApiParameters);
            $data=(array)json_decode($jsApiParameters);
            // file_put_contents("sign.txt", date("Y-m-d H:i:s") . "data   " .print_r($data, true). "\r\n", FILE_APPEND);

            unset($data['appId']);
            $this->ajax_r(1,'成功！',$data);
        }else{
            $this->ajax_r(0,'订单状态不正确，请检查！');
        }

    }

    public function wxnotify()
    {
        //使用通用通知接口
        $notify = new \Notify_pub();
        //存储微信的回调
        // $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
        $xml = file_get_contents('php://input');
        $store='wx_store_'.$this->store_id;
        $appid = C($store.'.WEIXIN_APP_KEY');
        $mch_id = C($store.'.WEIXIN_MCHID');
        $key= C($store.'.WEIXIN_MCHID_KEY');
        $notify->setAPPID($appid);
        $notify->setMCHID($mch_id);
        $notify->setMCHKEY($key);
        $notify->saveData($xml);
        // var_dump($xml);
        //验证签名，并回应微信。
        //对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
        //微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
        //尽可能提高通知的成功率，但微信不保证通知最终能成功。
        if($notify->checkSign() == FALSE){
            $notify->setReturnParameter("return_code","FAIL");//返回状态码
            $notify->setReturnParameter("return_msg","签名失败");//返回信息
        }else{
            $notify->setReturnParameter("return_code","SUCCESS");//设置返回码
        }
        $returnXml = $notify->returnXml();
        $parameter = $notify->xmlToArray($xml);
        $out_trade_no=$parameter['out_trade_no'];
        $out_trade_no=explode('_',$out_trade_no);
        $out_trade_no=$out_trade_no[0];
        //==商户根据实际情况设置相应的处理流程，此处仅作举例=======

        //以log文件形式记录回调信息
        //         $log_ = new Log_();
        $log_name= __ROOT__."/notify_url.log";//log文件路径

        log_result($log_name,"【接收到的notify通知】:\n".$xml."\n");

        if($notify->checkSign() == TRUE)
        {
            if ($notify->data["return_code"] == "FAIL") {
                //此处应该更新一下订单状态，商户自行增删操作
                log_result($log_name,"【通信出错】:\n".$xml."\n");
                echo 'error';
            }
            elseif($notify->data["result_code"] == "FAIL"){
                //此处应该更新一下订单状态，商户自行增删操作
                log_result($log_name,"【业务出错】:\n".$xml."\n");
                echo 'error';
            }
            else{
                //此处应该更新一下订单状态，商户自行增删操作
                $res=$notify->data["result_code"];
                switch($res){
                    case 'SUCCESS';
                        $status=get_order_status($out_trade_no,'10');
                        if($status){
                            update_order_status($out_trade_no, $out_trade_no,'20','微信');
                        }
                        log_result($log_name,"【支付成功】:\n".$xml."\n");
                        echo 'SUCCESS';
                        break;
                    case 'NOTPAY';
                        echo 'NOTPAY';
                        break;
                    default:
                        echo 'ERROR';
                        break;
                }
            }
        }
    }
    public function callback(){
        $getData = I('get.');
        $out_trade_no = $getData['order_no'];
        $trade_no = $getData['trade_no']?$getData['trade_no']:$getData['order_no'];
        $status = $getData['status']?$getData['status']:20;
        $payway = $getData['payway']?$getData['payway']:'微信';
        if (empty($trade_no) && empty($status)&&empty($out_trade_no)) {
            $datas['status'] = 0;
            $datas['message'] = '参数为空';
            $datas = json_encode($datas);
            die($datas);
        }
        $order = M('order');
        $flag=true;
        $result=$order->where('order_cn='.$out_trade_no)->select();
        if($result){
            $order_add_time=$result[0]['add_time'];
            foreach($result as $key=>$value){
                $data['order_id']=$value['order_id'];
                $data['pay_sn']=$trade_no;
                //免发货
                if($value['mian_send']==1&&$status==20){
                    //判断拼团是否成功
                    if($value['tuanselect']==1){
                        if($value['tuan_is_first_id']==0){
                            $num=get_tuan($value['order_id']);
                            $tuan_m_send['order_id']=$value['order_id'];
                        }else{
                            $num=get_tuan($value['tuan_is_first_id']);
                            $tuan_m_send['order_id']=$value['tuan_is_first_id'];
                        }
                        if($num==$value['tuannum']){
                            $data['order_state']='30';
                            $data['shipping_time']=time();
                            $tuan_m_send['status']=1;
                        }else{
                            $data['order_state']=$status;
                            $tuan_m_send['status']=0;
                        }
                    }else{
                        $data['order_state']='30';
                        $data['shipping_time']=time();
                    }
                }else{
                    $data['order_state']=$status;
                }
                $data['payment_code']=$payway;
                $data['payment_time']=time();
                $rs=$order->save($data);
                $uid=$value['buyer_id'];
                //减库存
                if($status==20){
                    $good_list=M('order_goods')->field('goods_id,goods_num,goods_pay_price,goods_sku,goods_sku_spec,goods_sku_style')->where('order_id='.$value['order_id'])->select();
                    foreach($good_list as $k=>$v){
                        if($v['goods_sku']==0){
                            M('shop')->where('id='.$v['goods_id'])->setDec('num',$v['goods_num']);
                        }else{
                            M('shop_sku')->where('sku_id='.$v['goods_sku'])->setDec('sku_stock',$v['goods_num']);
                            $sku_shop_info=M('shop')->find($v['goods_id']);
                            $sku=json_decode($sku_shop_info['shop_sku'],true);
                            $from=$sku['SKU_Form'];
                            foreach($from as $k2=>$v2){
                                if($v['goods_sku_spec']==$v2['sku_spec']&&$v['goods_sku_style']==$v2['sku_style']){
                                    $sku['SKU_Form'][$k2]['sku_stock']=$v2['sku_stock']-$v['goods_num'];
                                }
                            }
                            $update_sku['shop_sku']=json_encode($sku);
                            $update_sku['id']=$v['goods_id'];
                            M('shop')->save($update_sku);
                        }
                        //增加销量
                        M('shop')->where('id='.$v['goods_id'])->setInc('sale_num',$v['goods_num']);
                        //增加众筹销量和金额
                        M('crowdfunding')->where('goods_id='.$v['goods_id'])->setInc('num',$v['goods_num']);
                        M('crowdfunding')->where('goods_id='.$v['goods_id'])->setInc('now_money',$v['goods_pay_price']);


                    }
                }
                //判断拼团是否成功
                if($value['tuanselect']==1){
                    if($value['tuan_is_first_id']==0){
                        $num=get_tuan($value['order_id']);
                    }else{
                        $num=get_tuan($value['tuan_is_first_id']);
                    }
                    if($num==$value['tuannum']){
                        $newdata['tuan_is_success']=1;
                        //拼团成功时的订单肯定是子订单
                        $order->where('tuan_is_first_id='.$value['tuan_is_first_id'])->save($newdata);
                        $order->where('order_id='.$value['tuan_is_first_id'])->save($newdata);
                    }
                }
                if(!$rs){
                    $flag=false;
                }
            }
        }else{
            $result=$order->where('order_sn='.$out_trade_no)->find();
            $order_add_time=$result['add_time'];
            $data['order_id']=$result['order_id'];
            $data['pay_sn']=$trade_no;
            //免发货
            if($result['mian_send']==1&&$status==20){
                //判断拼团是否成功
                if($result['tuanselect']==1){
                    if($result['tuan_is_first_id']==0){
                        $num=get_tuan($result['order_id']);
                        $tuan_m_send['order_id']=$result['order_id'];
                    }else{
                        $num=get_tuan($result['tuan_is_first_id']);
                        $tuan_m_send['order_id']=$result['tuan_is_first_id'];
                    }
                    if($num==$result['tuannum']){
                        $data['order_state']='30';
                        $data['shipping_time']=time();

                        $tuan_m_send['status']=1;
                    }else{
                        $data['order_state']=$status;
                        $tuan_m_send['status']=0;
                    }
                }else{
                    $data['order_state']='30';
                    $data['shipping_time']=time();
                }
            }else{
                $data['order_state']=$status;
            }
            $data['payment_code']=$payway;
            $data['payment_time']=time();
            $rs=$order->save($data);
            $uid=$result['buyer_id'];
            //减库存
            if($status==20){
                $good_list=M('order_goods')->field('goods_id,goods_num,goods_pay_price,goods_sku,goods_sku_spec,goods_sku_style')->where('order_id='.$result['order_id'])->select();
                foreach($good_list as $k=>$v){
                    if($v['goods_sku']==0){
                        M('shop')->where('id='.$v['goods_id'])->setDec('num',$v['goods_num']);
                    }else{
                        M('shop_sku')->where('sku_id='.$v['goods_sku'])->setDec('sku_stock',$v['goods_num']);
                        $sku_shop_info=M('shop')->find($result['goods_id']);
                        $sku=json_decode($sku_shop_info['shop_sku'],true);
                        $from=$sku['SKU_Form'];
                        foreach($from as $k2=>$v2){
                            if($v['goods_sku_spec']==$v2['sku_spec']&&$v['goods_sku_style']==$v2['sku_style']){
                                $sku['SKU_Form'][$k2]['sku_stock']=$v2['sku_stock']-$v['goods_num'];
                            }
                        }
                        $update_sku['shop_sku']=json_encode($sku);
                        $update_sku['id']=$v['goods_id'];
                        M('shop')->save($update_sku);
                    }
                    //增加销量
                    M('shop')->where('id='.$v['goods_id'])->setInc('sale_num',$v['goods_num']);
                    //增加众筹销量和金额
                    M('crowdfunding')->where('goods_id='.$v['goods_id'])->setInc('num',$v['goods_num']);
                    M('crowdfunding')->where('goods_id='.$v['goods_id'])->setInc('now_money',$v['goods_pay_price']);

                }
            }
            //判断拼团是否成功
            if($result['tuanselect']==1){
                if($result['tuan_is_first_id']==0){
                    $num=get_tuan($result['order_id']);
                }else{
                    $num=get_tuan($result['tuan_is_first_id']);
                }
                if($num==$result['tuannum']){
                    $newdata['tuan_is_success']=1;
                    //拼团成功时的订单肯定是子订单
                    $order->where('tuan_is_first_id='.$result['tuan_is_first_id'])->save($newdata);
                    $order->where('order_id='.$result['tuan_is_first_id'])->save($newdata);
                }
            }
            if(!$rs){
                $flag=false;
            }
        }

        //团购免发货
        if($flag&&$tuan_m_send['status']==1){
            $m_data['order_state']='30';
            $m_data['shipping_time']=time();
            $order->where('tuan_is_first_id='.$tuan_m_send['order_id'])->save($m_data);
            $order->where('order_id='.$tuan_m_send['order_id'])->save($m_data);
        }
        //支付成功通知
        if($flag&&$status==20){

            $user_info=M('users')->find($uid);

            if($user_info['wx_h5openid']){
                $openid=$user_info['wx_h5openid'];
                $url='https://m.58daiyan.com/user/order_info/order/'.$out_trade_no;
                $keyword1=$out_trade_no;
                $keyword2=date('Y年m月d日  H:i',time());
                $keyword3=get_count_price($out_trade_no);
                $keyword4=$payway;
                send_info($openid,$url,$keyword1,$keyword2,$keyword3,$keyword4);
            }

        }

        //收货代言通知
        if($flag&&$status==40){

            $user_info=M('users')->find($uid);

            if($user_info['wx_h5openid']){
                $openid=$user_info['wx_h5openid'];
                $url='https://m.58daiyan.com/user/daiyan.html';
                $keyword1=date('Y年m月d日  H:i',$order_add_time);;
                $keyword2=$out_trade_no;
                send_info_daiyan($openid,$url,$keyword1,$keyword2);
            }

        }
        if($flag){
            $this->ajax_r(1,'成功！');
        }else{
            $this->ajax_r(0,'失败！');
        }
        //return $flag;
    }



    /**
     * 待付款订单需要的数据
     */
    public function orderInfo($uid,$store_id,$cart_ids)
    {
        $users_address=M('users_address');
        $useraddress=$users_address->where('user_id='.$uid.' and is_default=1')->find();
        $city_id=$useraddress['city'];

        $cart_list_id=explode(',',$cart_ids);

        $cartModel=M('cart');
        $shop_sku=M('shop_sku');
        $shop=M('shop');
        $store=M('store');
        $result=array();
        $total_num=$total_price=$daiyan_sale=$total_freight=0;$new_coupon_shop_ids=array();
        if(is_array($cart_list_id)){
            foreach($cart_list_id as $key =>$v){
                $cart=$cartModel->where('cart_id='.$v.' and store_id='.$store_id.' and buyer_id='.$uid)->find();
                if(!empty($cart)){
                    $rs_shop=$shop->find($cart['shop_id']);
                    $rs_store=$store->find($cart['store_id']);
                    $cart['freight']=get_freight($cart['shop_id'],$city_id,$cart['num']);
                    $cart['shop_picture'] = $rs_shop['image'];
                    $cart['shop_name'] = $rs_shop['title'];
                    if($cart['sku_id']!=0){
                        $rs_shop_sku=$shop_sku->where('sku_id='.$cart['sku_id'])->find();

                        $cart['sku_spec']=$rs_shop_sku['sku_spec'];
                        $cart['sku_style']=$rs_shop_sku['sku_style'];
                        if($cart['tuanselect']==1){
                            if($rs_shop_sku['sku_price_tuan']){
                                $price=$rs_shop_sku['sku_price_tuan'];
                            }else{
                                $price=$rs_shop['tuan_price'];
                            }
                        }else{
                            $price=$rs_shop_sku['sku_price'];
                        }
                    }else{
                        if($cart['tuanselect']=='1'){
                            $price= $rs_shop['tuan_price'];
                        }else{
                            $price= $rs_shop['price'];
                        }
                    }
                    //抵扣券
                    $shop_id=$cart['shop_id'];
                    $invoice=get_web_invoice();
                    $daiyan_start_time=time()-60*60*24*$invoice['web_diyong'];
                    $daiyan_info=M('daiyan')->where("uid=$uid and shop_id=$shop_id and time>$daiyan_start_time")->find();
                    if($daiyan_info){
                        $cart['daiyan_sale']=$rs_shop['dikouquan'];
                    }else{
                        $cart['daiyan_sale']=0;
                    }
                    //$cart['id']=$cart['shop_id'].','.$cart['sku_id'];
                    $cart['oprice']=$rs_shop['oprice'];
                    $cart['price']=$price;
                    if($cart['recommend_id']){
                        $cart['redenvelope']=$rs_shop['redenvelope'];
                    }
                    $daiyan_sale=$daiyan_sale+($cart['daiyan_sale']*$cart['num']);
                    $total_num=$total_num+$cart['num'];
                    $total_freight=$total_freight+$cart['freight'];
                    $total_price=$total_price+($cart['num']*$price)-($cart['num']*$cart['daiyan_sale']);
                    $cart_list[$key] =$cart;
                    $new_coupon_shop_ids[$key]=$cart['shop_id'];
                }
            }
            $result['total_freight'] = $total_freight;
            $result['daiyan_sale'] = $daiyan_sale;
            $result['total_num'] = $total_num;
            $result['total_price'] = $total_price;
            $result['new_coupon_shop_ids'] = implode(',',$new_coupon_shop_ids);
        }
        $result['cart_list']=$cart_list;
        return $result  ;
    }

    public function address($uid){
        $users=M('users');
        $users_address=M('users_address');
        if($uid){
            $userinfo=$users->find($uid);
            $useraddress=$users_address->where('user_id='.$uid.' and is_default=1')->limit(1)->select();
            foreach($useraddress as $key=>$value){
                $province=getProvinceInfo($value['province']);
                $city=getCityInfo($value['city']);
                $district=getDistrictInfo($value['district']);
                $useraddress[$key]['province']=$province['province_name'];
                $useraddress[$key]['city']=$city['city_name'];
                $useraddress[$key]['district']=$district['district_name'];
            }
            return $useraddress;
        }
    }

    //生成订单号
    public function build_order_no()
    {
        $no = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        //检测是否存在
        $db = M('order');
        $info = $db->where(array('order_sn'=>$no))->find();
        (!empty($info)) && $no = $this->build_order_no();
        return $no;

    }

    //查询订单
    public function orderQuery2($trade_no,$store_id)
    {
        $out_trade_no = $trade_no;
        //使用订单查询接口
        $orderQuery = new \OrderQuery_pub();
        //设置必填参数
        //appid已填,商户无需重复填写
        //mch_id已填,商户无需重复填写
        //noncestr已填,商户无需重复填写
        //sign已填,商户无需重复填写
        $orderQuery->setParameter("out_trade_no","$out_trade_no");//商户订单号
        //非必填参数，商户可根据实际情况选填
        //$orderQuery->setParameter("sub_mch_id","XXXX");//子商户号
        //$orderQuery->setParameter("transaction_id","XXXX");//微信订单号
        $store='wx_store_'.$store_id;
        $appid = C($store.'.WEIXIN_APP_KEY');
        $mch_id = C($store.'.WEIXIN_MCHID');
        $key= C($store.'.WEIXIN_MCHID_KEY');
        $orderQuery->setAPPID($appid);
        $orderQuery->setMCHID($mch_id);
        $orderQuery->setMCHKEY($key);
        //获取订单查询结果
        $orderQueryResult = $orderQuery->getResult();

        //商户根据实际情况设置相应的处理流程,此处仅作举例
        if ($orderQueryResult["return_code"] == "FAIL") {
            return false;
            die;
        }
        elseif($orderQueryResult["result_code"] == "FAIL"){
            return false;
            die;
        }
        else{
            $res=$orderQueryResult["trade_state"];
            switch($res){
                case 'SUCCESS';
                    $status=get_order_status($out_trade_no,'10');
                    if($status){
                        update_order_status($out_trade_no, $orderQueryResult["transaction_id"],'20','微信');
                        //dump($orderQueryResult);
                    }
                    return true;
                    break;
                case 'NOTPAY';
                    return false;
                    break;
                default:
                    return false;
                    break;
            }


        }

    }
    //生成linux系统随机数
    public function rd_session($len) {
        $fp = @fopen('/dev/urandom','rb');
        $result = '';
        if ($fp !== FALSE) {
            $result .= @fread($fp, $len);
            @fclose($fp);
        } else {
            trigger_error('Can not open /dev/urandom.');
        }
        $result = base64_encode($result);
        $result = strtr($result, '+/', '-_');
        return substr($result, 0, $len);
    }
    //获取openId
    public function getOpenId($code,$store_id)
    {
        $store='wx_store_'.$store_id;
        $appid = C($store.'.WEIXIN_APP_KEY');
        $appsecret = C($store.'.WEIXIN_APP_SECRET');
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret='.$appsecret.'&js_code='.$code .'&grant_type=authorization_code';
        $rs1 = file_get_contents($url);
        $rs = json_decode($rs1, TRUE);
        //\Think\Log::write("session :\n" . print_r($rs, true) . "\n",'storeApi/session' . date('Y-m-d'));
        if(empty($rs['errcode'])){
            $redis =connectRedis();
            $redis->set('session_key',$rs['session_key']);
            $redis->set('openid',$rs['openid']);
            return $rs;
        }else{
            return $rs;
        }
    }
    public function ajax_r($status='0',$message='',$data='') {
        $datas['status']=$status;
        $datas['message']=$message;
        $datas['data'] = $data;
        $datas = json_encode($datas);
        die($datas);
    }
}
?>
